import React, { FC, memo, useCallback, useContext } from 'react'
import { ACTIONS, AudioCtx, PlayMusicContext } from 'reducers/playMusic'
import { IMusicSong } from 'apis/types/personalized'
import { createMusic } from 'helpers/business'
import styles from './style.module.css'
import cn from 'classnames'
import { Icon } from '@blueprintjs/core'
import Artists from 'components/Artists'
import PlayIcon from 'components/PlayIcon'

interface IProps {
  id: number
  name: string
  picUrl: string
  song: IMusicSong
  index: number
}
const MusicItem: FC<IProps> = memo((item) => {
  const { id, name, picUrl, song, index } = item
  const [state, dispatch] = useContext(PlayMusicContext)
  const audioInfo = useContext(AudioCtx)
  const hasborderBottom = [4, 9].indexOf(index) > -1
  const playMusic = useCallback((id: number) => {
    dispatch({
      type: ACTIONS.PLAY,
      payload: {
        musicId: id,
        music: createMusic({
          ...item,
          artists: song.artists,
          duration: song.duration / 1000,
        }),
      },
    })
  }, [])
  const isMusicActive = state.muscid === id

  return (
    <div className={cn(styles.root, hasborderBottom && styles.boderBottom, isMusicActive && styles.active)}>
      <div className={styles.pic} onClick={() => playMusic(id)}>
        <img src={`${picUrl}?param=60y60`} loading='lazy' alt='' />
        <PlayIcon className={styles.playIcon} />
      </div>
      {isMusicActive ? (
        <div className={styles.isPlaying}>
          <Icon icon={audioInfo.state?.paused ? 'volume-off' : 'volume-up'} />
        </div>
      ) : (
        <div className={styles.order}> {index < 9 ? `0${index + 1}` : index + 1} </div>
      )}
      <div className={styles.info}>
        <div className={styles.name}>{name}</div>
        <Artists artists={song.artists} />
      </div>
    </div>
  )
})
export default MusicItem
